#!/bin/bash
# Comprehensive test script for enriginenc plugin
# Tests basic functionality, stability, and long-running scenarios

set -e

echo "=== Enrigin Encoder Comprehensive Test Script ==="
echo ""

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Test configuration
LONG_TEST=${LONG_TEST:-0}  # Set LONG_TEST=1 for extended stability tests
TEST_DURATION=${TEST_DURATION:-180}  # Duration for long test in seconds

# Check if plugin exists
echo -e "${YELLOW}[1/4] Checking plugin...${NC}"
if gst-inspect-1.0 enriginenc > /dev/null 2>&1; then
    echo -e "${GREEN}✓ enriginenc plugin found${NC}"
else
    echo -e "${RED}✗ enriginenc plugin not found${NC}"
    echo "Please build and install the plugin first:"
    echo "  cd build && make gstenriginenc"
    echo "  export GST_PLUGIN_PATH=\$(pwd):\$GST_PLUGIN_PATH"
    exit 1
fi

# Test 1: Basic H264 encoding
echo ""
echo -e "${YELLOW}[2/4] Test 1: Basic H264 VBR encoding...${NC}"
gst-launch-1.0 -q videotestsrc num-buffers=100 ! \
  video/x-raw,format=NV12,width=1280,height=720,framerate=30/1 ! \
  enriginenc codec=h264 rc-mode=vbr profile=high ! \
  h264parse ! mp4mux ! filesink location=test_basic.mp4

if [ -f test_basic.mp4 ]; then
    SIZE=$(stat -f%z test_basic.mp4 2>/dev/null || stat -c%s test_basic.mp4)
    echo -e "${GREEN}✓ Basic test passed (${SIZE} bytes)${NC}"
else
    echo -e "${RED}✗ Basic test failed${NC}"
    exit 1
fi

# Test 2: CBR encoding
echo ""
echo -e "${YELLOW}[3/4] Test 2: CBR 2Mbps encoding...${NC}"
gst-launch-1.0 -q videotestsrc num-buffers=100 ! \
  video/x-raw,format=NV12,width=1280,height=720,framerate=30/1 ! \
  enriginenc codec=h264 rc-mode=cbr bitrate=2000 profile=high ! \
  h264parse ! mp4mux ! filesink location=test_cbr.mp4

if [ -f test_cbr.mp4 ]; then
    SIZE=$(stat -f%z test_cbr.mp4 2>/dev/null || stat -c%s test_cbr.mp4)
    echo -e "${GREEN}✓ CBR test passed (${SIZE} bytes)${NC}"
else
    echo -e "${RED}✗ CBR test failed${NC}"
    exit 1
fi

# Test 3: HEVC encoding
echo ""
echo -e "${YELLOW}[4/4] Test 3: HEVC encoding...${NC}"
gst-launch-1.0 -q videotestsrc num-buffers=100 ! \
  video/x-raw,format=NV12,width=1280,height=720,framerate=30/1 ! \
  enriginenc codec=hevc rc-mode=cbr bitrate=2000 profile=main ! \
  h265parse ! mp4mux ! filesink location=test_hevc.mp4

if [ -f test_hevc.mp4 ]; then
    SIZE=$(stat -f%z test_hevc.mp4 2>/dev/null || stat -c%s test_hevc.mp4)
    echo -e "${GREEN}✓ HEVC test passed (${SIZE} bytes)${NC}"
else
    echo -e "${RED}✗ HEVC test failed${NC}"
    exit 1
fi

# Test 4: Long-running stability test (optional)
if [ "$LONG_TEST" = "1" ]; then
    echo ""
    echo -e "${BLUE}[LONG TEST] Stability test for ${TEST_DURATION}s ($(($TEST_DURATION / 60))min)...${NC}"
    echo "This test checks for black screen issues and encoder stability"
    
    # Calculate number of frames (30fps * duration)
    NUM_FRAMES=$((30 * TEST_DURATION))
    
    echo "Encoding ${NUM_FRAMES} frames at 30fps (MP4 format)..."
    # Test with MP4 format - the frame queue mechanism ensures stability
    GST_DEBUG=enriginenc:4 gst-launch-1.0 videotestsrc num-buffers=${NUM_FRAMES} pattern=ball ! \
      video/x-raw,format=NV12,width=1280,height=720,framerate=30/1 ! \
      enriginenc codec=h264 rc-mode=vbr bitrate=2000 profile=high ! \
      h264parse ! mp4mux ! filesink location=test_long.mp4 2>&1 | tee test_long.log
    
    if [ -f test_long.mp4 ]; then
        SIZE=$(stat -f%z test_long.mp4 2>/dev/null || stat -c%s test_long.mp4)
        SIZE_MB=$(awk "BEGIN {printf \"%.1f\", $SIZE / 1024 / 1024}")
        echo -e "${GREEN}✓ Long test passed (${SIZE_MB} MB MP4, ${NUM_FRAMES} frames expected)${NC}"
        
        # Verify video integrity
        echo "Verifying video integrity..."
        echo "  Expected frames: ${NUM_FRAMES}"
        echo "  Output file size: ${SIZE_MB} MB"
        
        # Check if size is reasonable (at least 1KB per frame on average)
        MIN_SIZE=$((NUM_FRAMES * 1000))
        if [ "$SIZE" -gt "$MIN_SIZE" ]; then
            echo -e "${GREEN}✓ Video size looks reasonable${NC}"
        else
            echo -e "${YELLOW}⚠ Video size seems small (${SIZE} bytes), possible frame drops${NC}"
        fi
        
        # Check for health check logs
        HEALTH_CHECKS=$(grep -c "Health check" test_long.log || true)
        echo "  Health check logs: ${HEALTH_CHECKS}"
        
        # Check for errors
        ERROR_COUNT=$(grep -c "ERROR\|pool exhausted\|avcodec.*failed" test_long.log || true)
        if [ "$ERROR_COUNT" -gt 0 ]; then
            echo -e "${RED}✗ Found ${ERROR_COUNT} errors in log${NC}"
            echo "Last 10 errors:"
            grep "ERROR\|pool exhausted\|avcodec.*failed" test_long.log | tail -10
        else
            echo -e "${GREEN}✓ No errors found${NC}"
        fi
    else
        echo -e "${RED}✗ Long test failed${NC}"
        exit 1
    fi
fi

# Test 6: Rapid start/stop test (stress test)
echo ""
echo -e "${YELLOW}[STRESS TEST] Rapid start/stop test...${NC}"
for i in {1..5}; do
    echo -n "  Run $i/5... "
    gst-launch-1.0 -q videotestsrc num-buffers=30 ! \
      video/x-raw,format=NV12,width=640,height=360,framerate=30/1 ! \
      enriginenc codec=h264 ! fakesink 2>/dev/null
    echo "OK"
done
echo -e "${GREEN}✓ Stress test passed (5 rapid start/stop cycles)${NC}"

# Test 7: Verify video files
echo ""
echo -e "${YELLOW}[VALIDATION] Checking generated videos...${NC}"
for video in test_basic.mp4 test_cbr.mp4 test_hevc.mp4; do
    if [ -f "$video" ]; then
        SIZE=$(stat -c%s "$video" 2>/dev/null || stat -f%z "$video" 2>/dev/null || echo "0")
        if [ "$SIZE" -gt 100000 ]; then
            SIZE_MB=$(awk "BEGIN {printf \"%.1f\", $SIZE / 1024 / 1024}")
            echo -e "  ${video}: ${GREEN}OK${NC} (${SIZE_MB} MB)"
        else
            echo -e "  ${video}: ${RED}FAILED${NC} (file too small or missing)"
        fi
    fi
done

# Summary
echo ""
echo -e "${GREEN}=== All tests completed ===${NC}"
echo ""
echo "Generated files:"
ls -lh test_*.mp4 2>/dev/null || true
echo ""
echo "To view the videos:"
echo "  ffplay test_basic.mp4"
echo "  ffplay test_cbr.mp4"
echo "  ffplay test_hevc.mp4"
if [ "$LONG_TEST" = "1" ] && [ -f test_long.mp4 ]; then
    echo "  ffplay test_long.mp4  # Long stability test (MP4 format)"
fi
echo ""
echo "To check video properties:"
echo "  ffprobe test_basic.mp4"
echo ""
echo "To run long stability test (3 minutes):"
echo "  LONG_TEST=1 ./test_enriginenc.sh"
echo ""
echo "To run custom duration test:"
echo "  LONG_TEST=1 TEST_DURATION=300 ./test_enriginenc.sh  # 5 minutes"
echo ""
echo "To clean up:"
echo "  rm test_*.mp4 test_*.h264 test_*.log"
